package network;

import org.omg.CORBA.portable.InputStream;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    private ServerSocket serverSocket =null;

    public TcpEchoServer (int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void  strat() throws IOException {
        System.out.println("服务器,启动!");
        while(true){
//            因为tcp是有连接的 所以需要通过 accept 方法 才能进行通信
            Socket clientSocket= serverSocket.accept();
            processConnection(clientSocket);
        }
    }
    private void processConnection(Socket clientSocket){
//        通过这个方法来处理一次连接,;连接建立过程中就会涉及到多次的请求相应交互.
        System.out.printf("[%s:%d] 客户端上线!", clientSocket.getInetAddress(),clientSocket.getPort());
//        循环读取客户端的请求并返回响应
        try(InputStream inputStream= (InputStream) clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner=new Scanner(inputStream);
            while(true){
                if (!scanner.hasNext()){
//                    读取完毕(客户端断开连接,就会产生读取完毕)
                    System.out.printf("[%s:%d] 客户端下线!",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //                1.读取请求并解析
                String request = scanner.next();
//                2.根据请求计算响应
                String response=process(request);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public String process (String request){
        return request;
    }
}
